package com.llu.aesAndDes;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Base64;

public class CommCrypto {

    public static final String IV_ALGORITHM = "1234567890123456";

    public static final String AES_CBC_PKCS5Padding = "AES/CBC/PKCS5Padding";
    public static final String AES_ECB_PKCS5Padding = "DES/CBC/PKCS5Padding";

    //AESkey

    //DESkey
    public static final String DES_KEY = "12345678";

    public static void main(String[] args) throws Exception {
        String key = AesTest.getKey();
        Key secretKey = new SecretKeySpec(Base64.getDecoder().decode(key), "AES");

        byte[] encrypt = encrypt("12345678".getBytes(), secretKey, AES_CBC_PKCS5Padding);
        System.out.println(new String(encrypt));

        byte[] decrypt = decrypt(encrypt, secretKey, AES_CBC_PKCS5Padding);
        System.out.println(new String(decrypt));


    }


    /**
     * 解密
     *
     * @param data
     *            待解密数据
     * @param key
     *            密钥
     * @param cipherAlgorithm
     *            加密算法/工作模式/填充方式
     * @return byte[] 解密数据
     * @throws Exception
     */
    public static byte[] decrypt(byte[] data, Key key, String cipherAlgorithm)
            throws Exception {
        // 实例化
        Cipher cipher = Cipher.getInstance(cipherAlgorithm);
        // byte[] ciphertextBytes = hexStringToByteArray(IV_ALGORITHM);
        // byte[] ivBytes = Arrays.copyOf(Arrays.copyOf(ciphertextBytes, 8),
        // 16);
        IvParameterSpec iv = new IvParameterSpec(IV_ALGORITHM.getBytes());// 使用CBC模式，需要一个向量iv，可增加加密算法的强度
        // 使用密钥初始化，设置为解密模式
        cipher.init(Cipher.DECRYPT_MODE, key, iv);
        // 执行操作
        return cipher.doFinal(data);
    }

    /**
     * 加密
     *
     * @param data
     *            待加密数据
     * @param key
     *            密钥
     * @param cipherAlgorithm
     *            加密算法/工作模式/填充方式
     * @return byte[] 加密数据
     * @throws Exception
     */
    public static byte[] encrypt(byte[] data, Key key, String cipherAlgorithm)
            throws Exception {
        // 实例化
        Cipher cipher = Cipher.getInstance(cipherAlgorithm);

        // byte[] ciphertextBytes = hexStringToByteArray(IV_ALGORITHM);
        // byte[] ivBytes = Arrays.copyOf(Arrays.copyOf(ciphertextBytes, 8),
        // 16);
        IvParameterSpec ivSpec = new IvParameterSpec(IV_ALGORITHM.getBytes());// 需要一个向量iv，可增加加密算法的强度
        // 使用密钥初始化，设置为加密模式
        cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
        // 执行操作
        return cipher.doFinal(data);
    }
}
